(function($) {

	Drupal.ajaxchatbox = {}
	Drupal.behaviors.ajaxchatbox = {
		attach: function(context, settings) {
			// Declare AJAX behavior for the form
			var options = {
        url: 'ajaxchatbox/send',
				//resetForm: true,
				beforeSubmit: Drupal.ajaxchatbox.validate,
				success: Drupal.ajaxchatbox.success
			};
			// Detect the message form
			var ajaxchatboxForm = $('#ajaxchatbox-message-form:not(.ajaxchatbox-processed)');
			if (ajaxchatboxForm.length) {
				// Set a class to the form indicating that it's been processed
				$(ajaxchatboxForm).addClass('ajaxchatbox-processed');
				// Add AJAX behavior to the form
				$(ajaxchatboxForm).ajaxForm(options);
				// Tell the form that we have Javascript enabled
				$(ajaxchatboxForm).find('#edit-js').val(1);
				// Empty the shout textfield
				$(ajaxchatboxForm).find('#edit-ajaxchatbox-message').val('');
				// Close errors if they're clicked
				$('#ajaxchatbox-error').click(function() {
					$(this).hide();
				});
				// Initialize the timer for shout updates
				Drupal.ajaxchatbox.messageTimer('start');
        // Scroll content bottom
        $("#ajaxchatbox-content").animate({ scrollTop: $('#ajaxchatbox-content')[0].scrollHeight}, 1000);
			}
		}
	};
	/**
	 * Callback for a successful shout submission
	 */
	Drupal.ajaxchatbox.success = function(responseText) {
		// Load the latest shouts
    if (responseText.msgid == 0) {
      var errorDiv = $('#ajaxchatbox-error');
      errorDiv.html(responseText.message);
			errorDiv.show();
    }
		Drupal.ajaxchatbox.loadMessages(true);
	}
	/**
	 * Starts or stops a timer that triggers every delay seconds.
	 */
	Drupal.ajaxchatbox.messageTimer = function(op) {
		var delay = Drupal.settings.ajaxchatbox.refreshDelay;
		if (delay > 0) {
			switch (op) {
			case 'start':
				Drupal.ajaxchatbox.interval = setInterval("Drupal.ajaxchatbox.loadMessages()", delay);
				break;
			case 'stop':
				clearInterval(Drupal.ajaxchatbox.interval);
				break;
			}
		}
	}
	/**
	 * Reloads all shouts from the server.
	 */
	Drupal.ajaxchatbox.loadMessages = function(restoreForm) {
		// Stop the timer
		Drupal.ajaxchatbox.messageTimer('stop');
		$.ajax({
			url: Drupal.settings.ajaxchatbox.updatePath,
			type: "GET",
			cache: "false",
			dataType: "html",
			data: {
				mode: Drupal.settings.ajaxchatbox.mode
			},
			success: function(html) {
				// Update the shouts
				$("#ajaxchatbox-content").html(html);
        $("#ajaxchatbox-content").animate({ scrollTop: $('#ajaxchatbox-content')[0].scrollHeight}, 1000);
				// Resume the timer
				Drupal.ajaxchatbox.messageTimer('start');
				// Hide any errors
				$('#ajaxchatbox-error').hide();
				// Restore the button
				if (restoreForm) {
					$('#ajaxchatbox-message-form input#edit-submit').show();
					$('#ajaxchatbox-throbber').hide();
				}
			},
			error: function() {
			}
		});
	}
	/**
	 * Validate input before submitting.
	 * Don't accept default values or empty strings.
	 */
	Drupal.ajaxchatbox.validate = function(formData, jqForm, options) {
		var errorMsg = '';
		var errorDiv = $('#ajaxchatbox-error');
		var form = jqForm[0];
		// Check if a message is present
		if ((!form.ajaxchatbox_message.value)) {
			errorMsg = Drupal.t('Enter a message');
		}
		// If a maxlength is set, enforce it
		if ((Drupal.settings.ajaxchatbox.maxLength > 0) && (form.ajaxchatbox_message.value.length > Drupal.settings.ajaxchatbox.maxLength)) {
			errorMsg = Drupal.t('The shout you entered is too long');
		}
		if (errorMsg) {
			// Show the message and stop heres
			errorDiv.html(errorMsg);
			errorDiv.show();
			return false;
		} else {
			// No errors registered, continue
			errorDiv.hide();
			errorDiv.html('');
		}


		// Clear the form input
		$('#edit-ajaxchatbox-message').val('');
		$('#ajaxchatbox-throbber').show();
		$('#ajaxchatbox-message-form input#edit-submit').hide();
		return true;
	};
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }
// Run function
  $(document).ready(function() {
/****************************************************************************/
    // Click event on each emotion
    $('#smiley-container img').click(function(){
      var title = $(this).attr('title');
      var k = title.replace(/([a-z0-9!\' ]*), /g, '');
      var msg = $('#edit-ajaxchatbox-message').val();
      msg = (msg.length ? msg + ' ' : '') + k;
      $('#edit-ajaxchatbox-message').val(msg);
      $('#edit-ajaxchatbox-message').setCursorPosition(msg.length);
      $('#edit-ajaxchatbox-message').focus();
    });
    $('#edit-ajaxchatbox-style-font-family option').each(function(item){
        $(this).css('font-family', $(this).attr('value'));
    });
    $('#edit-ajaxchatbox-style-color option').each(function(item){
        $(this).css('background-color', $(this).attr('value'));
    });
    $('#ajaxchatbox-message-form .form-type-checkbox').each(function(){
      if ($(this).find('input.form-checkbox').attr('checked') == true) {
        $(this).find('label').addClass('checked');
      }
      $(this).find('label').click(function(){
        var checkbox = $(this).parent('.form-type-checkbox').find('input.form-checkbox');
        if ($(checkbox).attr('checked') == true) {
          $(this).removeClass('checked');
        }
        else {
          $(this).addClass('checked');
        }
      });
    });
    $('#smiley-container .close').click(function(){
      $('#edit-smilies').addClass('collapsed');
      $('#edit-smilies .fieldset-wrapper').hide();
    });
/************************************************************************/
  });
})(jQuery);
